package com.vtb.thread;

import java.util.concurrent.BlockingQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.renren.api.client.param.impl.AccessToken;
import com.vtb.base.VtbBaseReadThread;
import com.vtb.entity.Config;
import com.vtb.entity.DataCache;
import com.vtb.entity.QqOauth;
import com.vtb.entity.RrOauth;
import com.vtb.entity.SsOauth;
import com.vtb.entity.Var;
import com.vtb.servlet.WtbException;
import com.vtb.utils.DateUtils;
import com.vtb.utils.MessageUtils;

public class RrReadThread extends VtbBaseReadThread{
	private static final Log log = LogFactory.getLog(RrReadThread.class);
	private JSONObject source_json;									   //新鲜事来源
	private RrOauth rrOauth = null;
	private JSONObject status = null;									//人人状态json
	private JSONArray attachment;										//包含照片的json数组
	private JSONObject photo;											//照片json
	public RrReadThread(BlockingQueue<Object> send_queue,BlockingQueue<RrOauth> traver_rrQueue) {
		this.send_queue = send_queue;
		this.traver_rrQueue = traver_rrQueue;
	}

	public void run() {
	    log.info(Thread.currentThread().getName()+"已启动");
		while (true) {
			log.debug("*********"+Thread.currentThread().getName()+"在工作！*************");
			try {
				rrOauth = traver_rrQueue.take();
				org.json.simple.JSONArray feed =client.getFeedService().getFeed("10,30", Long.valueOf(rrOauth.getUni()), 1, 1, new AccessToken(rrOauth.getAccess_token()));
				if (!feed.isEmpty()) {
					status = (JSONObject) feed.get(0);
				}
			} catch (Exception e) {
				log.error("获取人人新鲜事失败：", e);
				throw new WtbException("获取人人新鲜事失败", e);
			}
			log.debug("新鲜事:"+status);
			if (status != null) {
				praseResult(status);
			}

		}
	}

	/**
	 * 解析返回JSON 判断是否要发送
	 * @param resultJson
	 */
	private void praseResult(JSONObject resultJson){
		statusTime = (String) resultJson.get("update_time"); 	//格式为 2012-05-31 16:08:36
		if (resultJson.containsKey("source")) {					  	//包含来源
		    source_json = (JSONObject) resultJson.get("source");
		    source = (String) source_json.get("text");
			if (judgeSource(Config.RR_FROM)) {
	            return;
	        }
		}
		lastTime = DataCache.rrlastTime.get(rrOauth.getUni());	 //格式为20120531161302
		if (DateUtils.toMillins_(lastTime)/1000 < DateUtils.toMillins(statusTime)/1000) {  
			putToQueue(resultJson);
		}
	}
	
	/**
	 * 生成微博发送队列
	 * @param rrOauth
	 * @param status
	 */
	private void putToQueue(JSONObject status) {
		clone_mapq = DataCache.synCloneMap(QqOauth.class);
		clone_maps = DataCache.synCloneMap(SsOauth.class);
		
		QqOauth qqOauth = (QqOauth) clone_mapq.get(rrOauth.getRefq());
        SsOauth ssOauth = (SsOauth) clone_maps.get(rrOauth.getRefs());

		if (qqOauth == null && ssOauth == null) {
            return;
        }
		
		//上传图片新鲜事
		if ((Long)status.get("feed_type") == 30) {
			attachment = (JSONArray) status.get("attachment");
			if (attachment.size()>1) {
				return;     //上传多张照片 不去处理
			}else {
				photo = (JSONObject) attachment.get(0);
				image_url = (String) photo.get("raw_src");
				if (photo.containsKey("content")) {  //包含描述内容
					qqOauth.setMessage((String)photo.get("content"));
				}else{
					message = "#分享照片#";
				}
			}
		}
		//状态新鲜事
		if ((Long)status.get("feed_type")==10) {
			message = (String) status.get("message");
			//包含@某人 "转自"  或以“~” 不转发
			if (MessageUtils.cotainString(message, "@,转自")|| MessageUtils.lastIndex(message, "~")) {
				return;
			}

			//大于140个汉字 不转发
			if (message.length() > 280) {
				return;
			}
			message = MessageUtils.rr2qqExpression(message);
			//过滤表情后为空 不转发
			if (message == null || "".equals(message)) {
				return;
			}
		}
		qqOauth.setLastTime((DateUtils.toDateString((String) status.get("update_time"))));
		try {
			if (qqOauth != null) {
				if (rrOauth.getR2q().equals(Var.OPEN)) {
					qqOauth.setMessage(message);
	                qqOauth.setImageUrl(image_url);
	                send_queue.put(qqOauth);
	                log.debug("已加入腾讯微博发送队列");
				}
            }
			if (ssOauth != null) {
				if (rrOauth.getR2s().equals(Var.OPEN)) {
					ssOauth.setMessage(message);
					ssOauth.setImageUrl(image_url);
					send_queue.put(ssOauth);
					log.debug("已加入新浪微博发送队列");
				}
            }
		} catch (InterruptedException e) {
			log.error("放入微博队列失败：", e);
			throw new WtbException("放入微博队列失败", e);
		}
	}
}
